//
//  LoginViewController.swift
//  TinyShopKeeper
//
//  Created by rimi on 16/5/25.
//  Copyright © 2016年 yuying. All rights reserved.
//

import UIKit


let RecordPasswordSign:String = "RecordPasswordSign"
let PasswordSign:String = "PasswordSign"
let ShopIDSign:String = "ShopIDSign"
let AccountSign:String = "AccountSign"
let LoginSuccess:String = "LoginSuccess"

class LoginViewController: UIViewController {

 
    @IBOutlet weak var shopTextField: UITextField!
    @IBOutlet weak var accountTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var recordPasswordOrNotButton: UIButton!
    @IBOutlet weak var loginButton: UIButton!
    @IBOutlet weak var showPasswordOrNot: UIButton!
    
    
    @IBAction func recordOrNotAction(sender: UIButton) {
        
        sender.selected = !sender.selected
    }//记住密码
    
    @IBAction func showPasswordOrNot(sender: UIButton) {
        sender.selected = !sender.selected
        passwordTextField.secureTextEntry = !passwordTextField.secureTextEntry
        //解决光标在密码显隐状态不服帖
        let str = self.passwordTextField.text
        self.passwordTextField.text = ""
        self.passwordTextField.text = str
    }
    
 
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.loginButton.addBackgroundLayer(CGRectMake(0, 0, ScreenWidth*0.88, 45))
        self .readAccountData()//处理登录的数据
        self .addObservers()//键盘输入时的动画等
        recordPasswordOrNotButton.selected = true//运行后就是选中状态
        
    }

    
    func readAccountData()//处理登录的数据
    {let userDefaults = NSUserDefaults .standardUserDefaults()//数据存储
        if userDefaults .boolForKey(RecordPasswordSign){
            self .shopTextField .text = userDefaults .objectForKey(ShopIDSign) as? String
            self .accountTextField .text = userDefaults .objectForKey(AccountSign) as? String
            self .passwordTextField .text = userDefaults .objectForKey(PasswordSign) as? String
            
            
        }
        
    }
   
    //MARK: - Judge
    func judgeLogin(showMsg:Bool) -> Bool{//true提示用户
        var message:String? = ""
        if self.shopTextField.text?.characters.count == 0 || self.accountTextField.text?.characters.count == 0 || self.passwordTextField.text?.characters.count == 0{
            //空
            message = "店铺,工号或者密码为空"
            MBProgressHUD .showError(message)
        }
        return message?.characters.count != 0 ? false : true
        
        //或者好像可以是这样的
        //        var message:String? = ""
        //        if self.shopTextField.text?.characters.count == 0 || self.accountTextField.text?.characters.count == 0 || self.passwordTextField.text?.characters.count == 0{
        //            //空
        //            message = "店铺,工号或者密码为空"
        //
        //            if  message?.characters.count != 0{
        //                return true
        //            }
        //            MBProgressHUD .showError(message)
        //       
        //        return  false
        
        
    }
    
    //登录事件
    @IBAction func loginBtn(sender: UIButton) {
        
        if !self.judgeLogin(true) {//true表示返回为空~~需要提示用户
            return
        }
        
        var dic:[String:String] = loginParams()
        //        4、	shop_account：店铺帐户名，唯一
        //        5、	user_account：员工号
        //        6、	user_password：密码
        dic .updateValue(self.shopTextField.text!, forKey: "shop_account")//forKey根据接口文件而来
        dic .updateValue(self.accountTextField.text!, forKey: "user_account")
        dic .updateValue(self.passwordTextField.text!, forKey: "user_password")
        
        
        NetTool .requestX("登录中", urlString: LOGIN_URL, paramDictionary: dic, successAction: { (responseObject) -> Void in
            
            //网络请求成功时的处理， 根据接口文档和功能
            let result:[String:AnyObject] = responseObject as! [String:AnyObject]
            let resultCode = result["status"] as! String//错误代码
            let resultCodeIntValue = UInt(resultCode)
            
            //==0~来判断是根据接口文档和功能
            //
            //            "status": "0",//错误代码，0 — 表示没有错误
            //            "errorMsg": "",//成功，没有信息
            //            "body":
            
            if resultCodeIntValue == 0{
                //登录成功
                MBProgressHUD .showSuccess("登录成功！")
                
                //用户数据保存 //保存获取的数据信息(这里先在plist文件中添加第一个字段)
                self .loginSuccess(result["body"] as! [String:AnyObject])//
                
            }else{
                //登录失败
                MBProgressHUD .showError(result["errorMsg"] as! String)//errorMsg文件中
            }
            
            }) { (error) -> Void in
                
        }
        
        
        
        
//测试用~
//        self.willMoveToParentViewController(nil)//子控制器将被移除,所以父控制器就为nil
//        //判断login.view的父视图是否是rootVc.view
//        //是:移除login.view
//        //否:移除containerView ==(login.view.superView)
//        if self.view.superview == self.parentViewController?.view{
//            self.view.removeFromSuperview()
//        }else{
//            self.view.superview!.removeFromSuperview()
//        }
//        self.removeFromParentViewController()
    }
   
    func remeberOrRemovePassword()
    {
        if self.recordPasswordOrNotButton.selected{
            //选中状态记住密码
            UserDefaults .setObject(self.shopTextField.text!, forKey: ShopIDSign)
            UserDefaults .setObject(self.accountTextField.text!, forKey: AccountSign)
            UserDefaults .setObject(self.passwordTextField.text!, forKey: PasswordSign)
            
        }
        
        //记录 用户密码标示（标示是有没有记住密码,根据选中状态来）
        UserDefaults .setBool(self.recordPasswordOrNotButton.selected, forKey: RecordPasswordSign)
        
        //实时保存到硬盘
        UserDefaults .synchronize()//因为只有在app退出是才会将东西更新到硬盘
    }
    
    //登录成功
    func loginSuccess(result:[String:AnyObject])
    {
        //保存用户数据 + 店铺数据
        //放在prefix-Header中的简写如下：
        //        let UserInfo = MZUserInfo.userInfo//用户信息的单例
        //        let UserDefaults = NSUserDefaults .standardUserDefaults()
        //        let NotificationCenter = NSNotificationCenter .defaultCenter()
        //将字典转模型
        UserInfo.userShop = ShopModel .parse(dict: result["shop"] as! [String:AnyObject])
        let userDic = result["user"] as! [String:AnyObject]
        
        /*
        "user": {//已登录用户信息
        "mgr_base_id": "3",//登录员工id
        "mgr_shop_id": "11",//员工所属店铺id
        "mgr_type": "1",//员工类型：1=>'员工',2=>'店长',3=>'老板',99=>'管理员'
        "mgr_role_id": "5",//员工所属角色id
        "mgr_account": "001",//员工号
        "mgr_nickname": "老刘",//员工昵称
        "mgr_name": "刘林",//员工姓名
        "mgr_online": "2",//当前登录状态 0—未登录  1—android已登录  2—ios已登录  3—android及ios都已登录
        "mgr_login_token": "b5e9f2327f88843907c481b9f00ac59d",//授权访问令牌，后续功能调用均需要传递该访问令牌以验证是已登录的用户
        "role_name": "老板" //帐户所属角色名称
        },
        */
        UserInfo.mgrBaseId = userDic["mgr_base_id"] as? String
        UserInfo.mgrShopId = (userDic["mgr_shop_id"] as! String)
        UserInfo.accessToken = userDic["mgr_login_token"] as? String
        
        //修改登录标记
        UserInfo.loginSign = true
        //记住密码或移除密码
        self.remeberOrRemovePassword()
        

        
        //告知根控制器 登录成功 M可以让H显示相应数据
        let homeVc = self.parentViewController as! MainViewController
        homeVc .loginSuccess()
        
        
        
        //移除子控制器（登录页移除掉）
        //应用启动时：login.view ->containerview -> rootVc.view
        //注销时：login.view -> rootVc.view
        self .willMoveToParentViewController(nil)
        //判断login.view的父视图是否是 rootVc.view
        //是：移除login.view
        //否：移除占位的view( containerView )也就是login.view的super.view
        if self.view.superview == self.parentViewController?.view{
            
            self.view.removeFromSuperview()
            
        }else{
            
            self.view.superview?.removeFromSuperview()
        }
        
        
        self .removeFromParentViewController()//登录界面
    }
    
    
    //MARK:-- addObservers
    
    //析构函数
    deinit{
        NSNotificationCenter .defaultCenter() .removeObserver(self)
    }
    
    
    //键盘输入时的动画等
    func addObservers(){
        let notificationaCenter = NSNotificationCenter.defaultCenter()
        //键盘的frame的发生改变
        notificationaCenter .addObserver(self, selector: "keyboardFaremWillChange:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        //键盘将要隐藏
        notificationaCenter .addObserver(self, selector: "keyboardWillHidden:", name: UIKeyboardWillHideNotification, object: nil)
    }
    
    //键盘的frame的发生改变
    func keyboardFaremWillChange(notification:NSNotification){
        let dic = notification .userInfo
        self.viewChange(dic, hiddenSign: false)
        
        
        
    }
    
    //键盘将要隐藏
    func keyboardWillHidden(notification:NSNotification){
        let dic = notification .userInfo
        self.viewChange(dic, hiddenSign: true)
    }
    //动画
    func viewChange(dic:[NSObject:AnyObject]?,hiddenSign:Bool){
        //动画时长
        let duration = (dic![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber) .doubleValue
        //动画效果
        let intValue = (dic![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber) .unsignedIntegerValue
        let aimatonOption:UIViewAnimationOptions = UIViewAnimationOptions(rawValue: intValue)
        //键盘的frame
        let frame = (dic![UIKeyboardFrameEndUserInfoKey] as! NSValue) .CGRectValue()
        // 登录button底部空白的高度
        let distance =  ScreenHeight - (CGRectGetMaxY(self.loginButton.frame)+20)
        let disY = CGRectGetHeight(frame) - distance
        UIView .animateWithDuration(duration, delay: 0, options: aimatonOption, animations: { () -> Void in
            if hiddenSign{
                //键盘将要隐藏
                
                self.view.center = CGPointMake(ScreenWidth/2, ScreenHeight/2)
                
                
                
            }else{
                //键盘将要发生改变
                
                self.view.center = CGPointMake(ScreenWidth/2, ScreenHeight/2-disY)
                              
                
                
            }
            },completion: nil)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    
    
    //MARK: -- touch --
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
        
    }

}
